package com.fitso.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.fitso.model.bean.User;
import com.fitso.web.Constants;
import com.fitso.web.controller.UserController;

/**
 * <p>
 * Intercepts all requests and determines if the user has signed in, if not
 * redirects them to login a.k.a defaultUrl.
 * </p>
 * 
 * @author timothystorm
 * @see {@link UserController}
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	private List<String> _exclude;
	private String _defaultUrl = "/login";

	public void setExclude(List<String> exclude) {
		_exclude = exclude;
	}

	public void setDefaultUrl(String url) {
		_defaultUrl = url;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (exludeLogin(request, response)) {
			User user = (User) WebUtils.getSessionAttribute(request, Constants.SESSION_USER);
			if (user == null) {
				forwardToLogonPage(request, response);
			}
		}
		return true;
	}

	private boolean exludeLogin(HttpServletRequest request, HttpServletResponse response) {
		if (_exclude.contains(request.getServletPath()) && request.getPathInfo() == null) {
			return true;
		}
		return false;
	}

	private boolean forwardToLogonPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + _defaultUrl));
		return false;
	}
}
